package com.sunagy.demand.front.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * desc：#TODO fill me ！
 * author：三餘無夢生
 * date：2018/4/27
 * time：下午5:59
 */
public class FileUtil {
    /**
     * 获取唯一MD5哈希之后的文件名
     *
     * @param input
     * @return
     */
    public static String generateName(String input) {
        String suffix = FilenameUtils.getExtension(input);
        String realName = UUID.randomUUID().toString().replace("-", "");
        if (suffix.length() > 0)
            realName += "." + suffix;
        return realName;
    }

    /**
     * 获得真实上传地址
     *
     * @param path
     * @param request
     * @return
     */
    public static String getRealPath(String path,
                                     HttpServletRequest request) {
        File file = new File(request.getSession().getServletContext()
                .getRealPath("/"));
        return file.getParent() + File.separator
                + FilenameUtils.separatorsToSystem(path);
    }

    public static String getParent(String path) {
        File file = new File(path);
        return file.getParent();
    }

    /**
     * 上传一个文件到临时文件夹
     *
     * @param file
     * @return map
     * 		key=>original_name 原文件
     * 		key=>save_name 保存的文件名
     * @throws IOException
     */
    public static Map<String, Object> uploadToTmpDir(File file, String path)
            throws IOException {
        String realName = generateName(file.getName());

		/*  */
        File dirTest = new File(path);
        if (!dirTest.exists()) {
            if (!dirTest.mkdirs()) {
                throw new IOException("创建文件夹失败");
            }
        }

        File dir = new File(path, realName);

        FileUtils.copyFile(file, dir);

        Map<String, Object> dto = new HashMap<String, Object>();
        dto.put("original_name", file.getName());
        dto.put("save_name", realName);
        dto.put("size", file.length());

        return dto;
    }

    /**
     * 删除一个指定文件
     *
     * @param src
     * @param name
     */
    public static void deleteFile(String src, String name) {
        File file = new File(src, name);
        if (file.exists())
            FileUtils.deleteQuietly(file);
    }
}
